package com.yunzheng.interceptor;


import com.yunzheng.common.BaseResult;
import com.yunzheng.constants.SystemConstants;
import com.yunzheng.enums.ResultStatuesEnums;
import com.yunzheng.redis.RedisManager;
import com.yunzheng.util.MapperUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * <p>
 * 登录拦截
 * </p>
 *
 * @author 杜奕明
 * @date 2019/11/24
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisManager redisManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader(SystemConstants.TOKEN);
        // 没有传token
        if (StringUtils.isBlank(token)) {
            response.setContentType("application/json");
            response.getWriter().print(MapperUtil.obj2json(BaseResult.notOk(ResultStatuesEnums.NOT_LOGIN)));
            return false;
        }

        // token过期或没有对应的userId
        String userId = String.valueOf(redisManager.get(token));
        if (StringUtils.isBlank(userId)) {
            response.setContentType("application/json");
            response.getWriter().print(MapperUtil.obj2json(BaseResult.notOk(ResultStatuesEnums.BAD_TOKEN)));
            return false;
        }

        return true;
    }
}

